const express=require('express')
const Router=express.Router()
const model = require('./model')
const User = model.getModel('user')

Router.get('/list',function(req,res){
    // User.remove({}, function (e, d) { })
    User.find({},function(e,d){
        return res.json({code:0,data:d})
    })
})

Router.post('/login',function(req,res){
    const{user,pwd}=req.body
    User.findOne({user,pwd},function(err,doc){
        if (!doc){
            return res.json({code:1,msg:'用户不存在'})   
        }
        res.cookie('userid',doc._id)
        return res.json({ code: 0, data: doc })  
        
    })
})
Router.post('/register',function(req,res){
    const{user,pwd,time}=req.body 
    User.findOne({ user, pwd, time},function(err,doc){
        if(doc){
            return res.json({code:1,msg:'用户已经存在'})
        }
        const newModel = new User({ user, pwd, time})
        newModel.save(function(err,doc){
            if (err) {
                return res.json({ code: 1, msg: '后端出错' })
            }
            res.cookie('userid', doc._id)
            return res.json({ code: 0, data: { user, pwd, time}})
        })
    })
})
Router.post('/updata', function (req, res) {
    const { userid } = req.cookies
    if (!userid) {
        return res.json({ code: 1 })
    }
    const body = req.body
    User.findByIdAndUpdate(userid, body, function (err, doc) {
        const data = Object.assign({}, {
            user: doc.user,
            pwd: doc.pwd,
            time:doc.time
        }, body)
        return res.json({ code: 0, data: data })
    })
})
Router.get('/info', function (req, res) {
    const { userid } = req.cookies
    if(!userid){
        return res.json({ code: 1, msg: '后端出错' })
    }
    User.findOne({_id:userid},function(err,doc){
        if(doc){
            return res.json({ code: 0, data:doc})
        } 
    })

})


module.exports=Router